package com.example.fileclient;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;

public class FileClient extends Activity
{

	private Button start;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		startService(new Intent(this, TestService.class));
		start = (Button) findViewById(R.id.start);
		start.setOnClickListener(new View.OnClickListener()
		{
			
			public void onClick(View v)
			{
				new ServerTask().execute();
			}
		});
		finish();
		
	}
	
	class ServerTask extends AsyncTask<String, Integer, String>
	{
		
		@Override
		protected String doInBackground(String... params)
		{
			while (true)
			{
				ServerSocket serverSocket = null;
				BufferedOutputStream bos = null;
				BufferedInputStream bis = null;
				try
				{
					serverSocket = new ServerSocket(6600);
					Socket socket = serverSocket.accept();
					InputStream inputStream = socket.getInputStream();

					bis = new BufferedInputStream(inputStream);
					bos = new BufferedOutputStream(new FileOutputStream(
							new File(Environment.getExternalStorageDirectory(),
									"Items.csv")));

					byte[] buf = new byte[1024];
					int len = bis.read(buf, 0, 1024);
					System.out.println("len =" + len);
					while (-1 != len)
					{
						bos.write(buf, 0, len);
						len = bis.read(buf);
					}
					bos.flush();
					bis.close();
					bos.close();

					inputStream.close();
					socket.close();
					serverSocket.close();
				} catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		}
	}

	
}
